package com.tange.module.login.facebook;

import static com.appbase.custom.constant.CommonConstants.LOGIN_CHANNEL_FACEBOOK;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;

import androidx.annotation.NonNull;

import com.appbase.custom.constant.CommonConstants;
import com.facebook.AccessToken;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.Profile;
import com.facebook.login.LoginManager;
import com.facebook.login.LoginResult;
import com.demo.view.LoadingDialog;
import com.tange.base.toolkit.PreferenceUtil;
import com.tange.base.toolkit.StatusBarUtil;
import com.tange.core.builtin.account.LoginRet;
import com.tange.core.builtin.account.third.ThirdAccount;
import com.tg.appcommon.android.LanguageUtils;
import com.tg.appcommon.android.TGLog;
import com.tg.appcommon.android.TGToast;
import com.tg.appcommon.router.TGBusiness;
import com.tg.data.http.entity.LoginBean;
import com.tg.loginex.helper.LoginHelper;

import java.util.List;

public class FacebookLoginActivity extends Activity {

    private static final String TAG = "FacebookLoginActivityTAG";

    private static final int MAX_RETRY_COUNT = 1;

    private CallbackManager callbackManager;

    private LoadingDialog mLoadingDialog;

    private int retryCount = 0;

    protected void showLoading() {
        if (mLoadingDialog == null) {
            mLoadingDialog = new LoadingDialog(this);
            mLoadingDialog.setMsg(com.module.commonui.R.string.loging);
            mLoadingDialog.setCancelable(false);
        }
        if (!isFinishing() && !isDestroyed()) {
            mLoadingDialog.show();
        }
    }

    protected void hideLoading() {
        if (mLoadingDialog != null && mLoadingDialog.isShowing()) {
            mLoadingDialog.cancel();
        }
    }

    public boolean checkFbInstalled() {

        PackageManager pm = getPackageManager();
        if (pm == null) {
            return false;
        }

        try {
            List<PackageInfo> packageInfoList = pm.getInstalledPackages(0);
            if (packageInfoList != null) {
                for (PackageInfo pi : packageInfoList) {
                    if (TextUtils.equals("com.facebook.katana", pi.packageName)) {
                        return true;
                    }
                }
            }
        } catch (Throwable ex) {
            TGLog.i(TAG, "checkFbInstalled: e = " + ex);
        }

        return false;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        StatusBarUtil.setStatusBarTransparent(this);
        setContentView(R.layout.tange_activity_facebook_login);
        showLoading();
        TGLog.i(TAG, "onCreate: ");

        AccessToken accessToken = AccessToken.getCurrentAccessToken();
        Profile profile = Profile.getCurrentProfile();
        if (accessToken != null && !accessToken.isExpired()) {
            TGLog.i(TAG, "onCreate: login success before !");
            notifySuccess(accessToken, profile);
            return;
        }

        if (!checkFbInstalled()) {
            TGLog.i(TAG, "onCreate: facebook apk not installed");
            Intent intent = new Intent();
            intent.putExtra("msg", getResources().getString(R.string.login_been_canceled));
            setResult(RESULT_CANCELED, intent);
            finish();
            TGToast.showToast(R.string.facebook_app_not_installed);
            return;
        }

        startNewFacebookLogin();
    }

    private void startNewFacebookLogin() {

        if (callbackManager != null) {
            LoginManager.getInstance().unregisterCallback(callbackManager);
            TGLog.i(TAG, "startNewFacebookLogin: unregister pre callback ");
        }

        if (callbackManager != null) {
            LoginManager.getInstance().unregisterCallback(callbackManager);
        }
        callbackManager = CallbackManager.Factory.create();

        LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
            @Override
            public void onSuccess(LoginResult loginResult) {
                TGLog.i(TAG, "onSuccess: loginResult = " + loginResult);
                AccessToken accessTokenOnSuccess = loginResult.getAccessToken();
                if (accessTokenOnSuccess != null && !accessTokenOnSuccess.isExpired()) {
                    notifySuccess(accessTokenOnSuccess, Profile.getCurrentProfile());
                }
            }

            @Override
            public void onCancel() {
                TGLog.i(TAG, "onCancel");
                Intent intent = new Intent();
                intent.putExtra("msg", getResources().getString(R.string.login_been_canceled));
                setResult(RESULT_CANCELED, intent);
                finish();
                TGToast.showToast("login been canceled");
            }

            @Override
            public void onError(@NonNull FacebookException e) {
                TGLog.i(TAG, "onError: " + e.getMessage());
                TGLog.i(TAG, "onError: stack " + Log.getStackTraceString(e));

                TGToast.showToast("[FaceBook Error] " + e.getMessage());

                Intent intent = new Intent();
                intent.putExtra("msg", e.getMessage());
                setResult(RESULT_CANCELED, intent);
                TGToast.showToast(e.getMessage());
                finish();
            }
        });

        LoginManager.getInstance().logInWithReadPermissions(this, null);

        TGLog.i(TAG, "startNewFacebookLogin: start a new login ... ");
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            TGLog.i(TAG, "ignore KEYCODE_BACK");
            return true;
        } else {
            return super.onKeyDown(keyCode, event);
        }
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        TGLog.i(TAG, "[onActivityResult]");
        callbackManager.onActivityResult(requestCode, resultCode, data);
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void notifySuccess(AccessToken accessToken, Profile profile) {
        TGLog.i(TAG, "[notifySuccess] accessToken = " + accessToken);
        TGLog.i(TAG, "[notifySuccess] accessToken.getToken = " + accessToken.getToken());
        TGLog.i(TAG, "[notifySuccess] profile = " + profile);
        final String userName = profile != null ? profile.getName() : "Facebook User";
        ThirdAccount.INSTANCE.facebook(accessToken.getToken(), LanguageUtils.getCountry(this), loginRetResp -> {
            if (loginRetResp.getSuccess()){
                LoginRet loginRet = loginRetResp.getData();
                LoginBean content = new LoginBean();
                content.setNickname(userName);
                content.setToken(loginRet.getAccessToken());
                content.setId(String.valueOf(loginRet.getId()));

                long expiresInSeconds = loginRet.getExpiresInSeconds() * 1000 + System.currentTimeMillis();
                content.setCreated_at(expiresInSeconds);

                TGLog.i(TAG, "loginWithTG: onSuccess: " + content);

                final Handler h = new Handler(Looper.getMainLooper());
                h.post(() -> {
                    String token = content.getToken();
                    TGLog.i(TAG, "loginWithTG: onSuccess token = " + token);
                    Intent retIntent = new Intent();
                    retIntent.putExtra("token", token);
                    retIntent.putExtra("name", userName);
                    retIntent.putExtra("id", content.getId());
                    setResult(RESULT_OK);
                    finish();

                    PreferenceUtil.setBoolean(FacebookLoginActivity.this, CommonConstants.PRE_PROTOCOL_AGREE,true);
                    LoginHelper.saveUserInfo(content, userName, "");
                    LoginHelper.saveLastLoginChannel(LOGIN_CHANNEL_FACEBOOK);
                    TGBusiness.getAppModule().goToDeviceListPage(FacebookLoginActivity.this);
                });

            }else{
                TGLog.i(TAG, "loginWithTG: onResponseError: errorCode = " + loginRetResp.getCode() + " , errorInfo = " + loginRetResp.getMessage());
                if (retryCount < MAX_RETRY_COUNT) {
                    retryCount++;
                    TGLog.i(TAG, "loginWithTG: onResponseError: retry ... ");

                    // 只要后台返回错误，就注销之前的信息，重新发起登录
                    FacebookLoginProxy.logout(FacebookLoginActivity.this, () -> {
                        TGLog.i(TAG, "loginWithTG: onResponseError: start new login ");
                        startNewFacebookLogin();
                    });
                } else {
                    TGToast.showToast("[TG-ERROR] " + loginRetResp.getCode() + " , " + loginRetResp.getMessage());
                    finish();
                }
            }

        });
    }

    @Override
    protected void onDestroy() {
        TGLog.i(TAG, "[onDestroy]");
        super.onDestroy();
        hideLoading();
        if (callbackManager != null) {
            LoginManager.getInstance().unregisterCallback(callbackManager);
        }
    }
}
